package com.aztec.ims.service.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;

import com.aztec.ims.domain.CustomInformation;
import com.aztec.ims.service.om.CustomInfo;
import com.aztec.ims.service.response.GenericResponse;
import com.aztec.ims.service.util.HibernateUtil;

public class CustomInfoDao {
	public GenericResponse createCustomInfo(Map request,char type,String id) {
		List<CustomInfo> omList = convertRequestToOm(request,type,id);

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		for(int i=0;i<omList.size();i++)
		  session.save(omList.get(i));
		session.getTransaction().commit();

		GenericResponse response = new GenericResponse(null);
		return response;
	}

	public Map<String,CustomInformation> getCustomInfo(char type,String id) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(CustomInfo.class);
		criteria.add(Expression.eq("fieldType", new Character(type)));
		criteria.add(Expression.eq("parentId", new Integer(id)));
		criteria.addOrder(Order.asc("customInfoId"));
		List results = criteria.list();
		session.getTransaction().commit();

		return convertOmToResponse(results);

	}

	private Map<String,CustomInformation> convertOmToResponse(List results) {
		Map<String,CustomInformation> response = new HashMap<String, CustomInformation>();

		if (results != null) {
			for (Iterator iter = results.iterator(); iter.hasNext();) {
				CustomInfo om = (CustomInfo) iter.next();
				CustomInformation domain = new CustomInformation(om.getFieldName(),om.getFieldValue());
				response.put(om.getCustomInfoId().toString(),domain);
			}
		}

		return response;
	}

	private List<CustomInfo> convertRequestToOm(
			Map<String,CustomInformation> request,char type,String id) {
		
		List<CustomInfo> omList = new ArrayList<CustomInfo>();
		if(request != null && request.values()!= null){
			for(Iterator iter = request.values().iterator();iter.hasNext();){
				CustomInformation domain = (CustomInformation)iter.next();
				CustomInfo om = new CustomInfo(domain.getName(),new Integer(id),new Character(type),domain.getValue());
				omList.add(om);
			}
		}
		return omList;
	}
}
